import React from 'react'
import { Breadcrumb as AntBreadcrumb } from 'antd'
import { Link, useLocation } from 'react-router-dom'
import { HomeOutlined } from '@ant-design/icons'

interface BreadcrumbConfig {
  [key: string]: {
    name: string
    icon?: React.ReactNode
  }
}

const breadcrumbConfig: BreadcrumbConfig = {
  dashboard: { name: '首页', icon: <HomeOutlined /> },
  projects: { name: '项目' },
  editor: { name: '编辑器' },
  templates: { name: '模板' },
  analytics: { name: '分析' },
  settings: { name: '设置' },
  profile: { name: '个人中心' },
  'forgot-password': { name: '忘记密码' },
  auth: { name: '认证' },
  login: { name: '登录' },
  register: { name: '注册' }
}

interface BreadcrumbProps {
  customItems?: Array<{
    path?: string
    name: string
  }>
}

const Breadcrumb: React.FC<BreadcrumbProps> = ({ customItems }) => {
  const location = useLocation()

  const getBreadcrumbItems = () => {
    if (customItems) {
      return [
        {
          title: (
            <Link to="/dashboard">
              <HomeOutlined className="mr-1" />
              首页
            </Link>
          )
        },
        ...customItems.map((item, index) => ({
          title: item.path && index < customItems.length - 1 ? (
            <Link to={item.path}>{item.name}</Link>
          ) : (
            item.name
          )
        }))
      ]
    }

    const pathSegments = location.pathname.split('/').filter(Boolean)
    
    if (pathSegments.length === 0 || pathSegments[0] === 'dashboard') {
      return [
        {
          title: (
            <span>
              <HomeOutlined className="mr-1" />
              首页
            </span>
          )
        }
      ]
    }

    const items = [
      {
        title: (
          <Link to="/dashboard">
            <HomeOutlined className="mr-1" />
            首页
          </Link>
        )
      }
    ]

    let path = ''
    pathSegments.forEach((segment, index) => {
      path += `/${segment}`
      const isLast = index === pathSegments.length - 1
      const config = breadcrumbConfig[segment]
      const name = config?.name || segment.charAt(0).toUpperCase() + segment.slice(1)

      if (!isLast) {
        items.push({
          title: <Link to={path}>{name}</Link>
        })
      } else {
        items.push({
          title: name
        })
      }
    })

    return items
  }

  return (
    <AntBreadcrumb 
      items={getBreadcrumbItems()} 
      className="text-sm"
    />
  )
}

export default Breadcrumb